﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using TodayWhoModel;
using System.Web.Services;
using System.Collections;
using System.Collections.Specialized;
using System.Text.RegularExpressions;

namespace TodayWho
{
    public partial class add : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            UserModel user = new UserModel();
            string userName = Request.QueryString["u"];
            user.UserName = userName;
            if (userName == "general" || userName == "music" || userName == "sport" || userName == "arts" || userName == "literature" || userName == "tech") // categories
            {
                user.RetrieveTodaysUserWithCategory(userName);

            }
            else if (string.IsNullOrEmpty(userName))
            {
                Response.Redirect("404.aspx");
            }
            else
            {
                user.RetrieveUserInfoWithUserNameForAccount();
                
            }
            if (String.IsNullOrEmpty(user.Email))
            {
                Response.Redirect("404.aspx");
            }
            
            SetOpenGraphMetaTags(user);
            SetPageTitle(user);
        }

        [WebMethod]
        public static string Save(string key, string value)
        {   
            bool res=false;
            UserModel user = new UserModel();
            user.UserId = Convert.ToInt32(HttpContext.Current.Session["userId"].ToString());
            if (key.CompareTo("nameSurname") == 0 || key.CompareTo("title") == 0 || key.CompareTo("shortDesc") == 0 || key.CompareTo("photoUrl1") == 0 || key.CompareTo("isTherePhoto") == 0 || key.CompareTo("isPhotoUsed") == 0) // nameSurname, title, shortDesc, photoUrl
            {
                res = user.UpdateField(key, value);
            }
            else if (key.CompareTo("service") == 0) // services
            {
                key = value.Split('^')[0];
                value = value.Split('^')[1];
                res = user.UpdateField(key, value);
            }
            else // userPrefs like color,size etc
            {
                UserPreferencesModel userPrefs = new UserPreferencesModel();
                userPrefs.UserId = user.UserId;
                res = userPrefs.UpdatePref(key, value);
            } 

            return res.ToString();
        }

        [WebMethod]
        public static ArrayList InitializeUser()
        {
            UserModel user = new UserModel();
            bool isDraggable = false;
            NameValueCollection collection = GetQueryStringCollection(HttpContext.Current.Request.UrlReferrer.Query);
         
            string userName = HttpContext.Current.Server.UrlDecode(collection["u"]);
            if (string.IsNullOrEmpty(userName))
            {
                throw new Exception("user name cannot found");
            }
            else if (userName == "general" || userName == "music" || userName == "sport" || userName == "arts" || userName == "literature" || userName == "tech") // categories
            {
                //GetTodaysCategoryInfo(userName);
                /* retrieve user name of the category for that time */ 
            }
            else // user page
            {
                if (HttpContext.Current.Session["userName"] != null) // user loggedin
                {
                    if (userName == HttpContext.Current.Session["userName"].ToString()) // if in his page, set draggable true
                    {
                        isDraggable = true;
                    }
                }  
            }

            user.UserName = userName;
            user.RetrieveUserInfoWithUserNameForAccount();
            if (String.IsNullOrEmpty(user.Email))
            {
                throw new Exception("email cant found");
            }

            user.Password = "";
            user.Email = "";
            ArrangeserviceLinks(user);

            if (!isDraggable) // if user is not looking his page
            {
                // increment pageview here // 
                PageviewModel pageview = new PageviewModel();
                pageview.UserId = user.UserId;
                pageview.UpdatePageview();
                // increment pageview end //
            }
           
            ArrayList list = new ArrayList();
            list.Add(user);
            UserPreferencesModel userPrefs = new UserPreferencesModel();
            userPrefs.UserId = user.UserId;
            userPrefs.RetrieveUserPreferences();
            list.Add(userPrefs);
            list.Add(isDraggable);
            return list;
        }


        //Get Querystring name value collection  
        public static NameValueCollection GetQueryStringCollection(string url)
        {
            string keyValue = string.Empty;
            NameValueCollection collection = new NameValueCollection();
            string[] querystrings = url.Split('&');
            if (querystrings != null && querystrings.Count() > 0)
            {
                for (int i = 0; i < querystrings.Count(); i++)
                {
                    string[] pair = querystrings[i].Split('=');
                    collection.Add(pair[0].Trim('?'), pair[1]);
                }
            }
            return collection;
        }

        private void SetOpenGraphMetaTags(UserModel user)
        {
            HtmlMeta metaTitle = new HtmlMeta();
            metaTitle.Attributes.Add("property", "og:title");
            metaTitle.Attributes.Add("content", user.NameSurname + " | TodayWho");
            this.Header.Controls.Add(metaTitle);

            HtmlMeta metaType = new HtmlMeta();
            metaType.Attributes.Add("property", "og:type");
            metaType.Attributes.Add("content", "public_figure");
            this.Header.Controls.Add(metaType);

            HtmlMeta metaAdmin = new HtmlMeta();
            metaAdmin.Attributes.Add("property", "fb:admins");
            metaAdmin.Attributes.Add("content", "563383238");
            this.Header.Controls.Add(metaAdmin);

            HtmlMeta metaUrl = new HtmlMeta();
            metaUrl.Attributes.Add("property", "og:url");
            metaUrl.Attributes.Add("content", "http://todaywho.com/" + user.UserName);
            this.Header.Controls.Add(metaUrl);

            HtmlMeta metaImage = new HtmlMeta();
            metaImage.Attributes.Add("property", "og:image");
            metaImage.Attributes.Add("content", "http://todaywho.com" + user.PhotoUrl1);
            this.Header.Controls.Add(metaImage);

            HtmlMeta metaSite = new HtmlMeta();
            metaSite.Attributes.Add("property", "og:site");
            metaSite.Attributes.Add("content", "TodayWho");
            this.Header.Controls.Add(metaSite);

            HtmlMeta metaDesc = new HtmlMeta();
            metaDesc.Attributes.Add("property", "og:description");
            metaDesc.Attributes.Add("content", user.ShortDesc);
            this.Header.Controls.Add(metaDesc);

            // for g+
            HtmlMeta metaNameGplus = new HtmlMeta();
            metaNameGplus.Attributes.Add("itemprop", "name");
            metaNameGplus.Attributes.Add("content", user.NameSurname);
            this.Header.Controls.Add(metaNameGplus);

            HtmlMeta metaDescGplus = new HtmlMeta();
            metaDescGplus.Attributes.Add("itemprop", "description");
            metaDescGplus.Attributes.Add("content", user.ShortDesc);
            this.Header.Controls.Add(metaDescGplus);

            HtmlMeta metaImageGplus = new HtmlMeta();
            metaImageGplus.Attributes.Add("itemprop", "image");
            metaImageGplus.Attributes.Add("content", "http://todaywho.com" + user.PhotoUrl1);
            this.Header.Controls.Add(metaImageGplus);
        }

        private void SetPageTitle(UserModel user)
        {
            Page.Title = user.NameSurname + " | TodayWho";
        }

        private static void ArrangeserviceLinks(UserModel user)
        {   
            string sPattern = "^(http|https)://";
            if (!string.IsNullOrEmpty(user.Facebook))
            {   
                if (!Regex.IsMatch(user.Facebook, sPattern))
                {
                        user.Facebook = "http://"+user.Facebook;
                }
                user.Facebook = "/r.aspx?r=" + user.Facebook + "&u=" + user.UserName + "&s=facebook";
            }
            if (!string.IsNullOrEmpty(user.Twitter))
            {
                if (!Regex.IsMatch(user.Twitter, sPattern))
                {
                    user.Twitter = "http://" + user.Twitter;
                }
                user.Twitter = "/r.aspx?r=" + user.Twitter + "&u=" + user.UserName + "&s=twitter";
            }
            if (!string.IsNullOrEmpty(user.Blogger))
            {
                if (!Regex.IsMatch(user.Blogger, sPattern))
                {
                    user.Blogger = "http://" + user.Blogger;
                }
                user.Blogger = "/r.aspx?r=" + user.Blogger + "&u=" + user.UserName + "&s=blogger";
            }
            if (!string.IsNullOrEmpty(user.Wordpress))
            {
                if (!Regex.IsMatch(user.Wordpress, sPattern))
                {
                    user.Wordpress = "http://" + user.Wordpress;
                }
                user.Wordpress = "/r.aspx?r=" + user.Wordpress + "&u=" + user.UserName + "&s=wordpress";
            }
            if (!string.IsNullOrEmpty(user.Linkedin))
            {
                if (!Regex.IsMatch(user.Linkedin, sPattern))
                {
                    user.Linkedin = "http://" + user.Linkedin;
                }
                user.Linkedin = "/r.aspx?r=" + user.Linkedin + "&u=" + user.UserName + "&s=linkedin";
            }
            if (!string.IsNullOrEmpty(user.Tumblr))
            {
                if (!Regex.IsMatch(user.Tumblr, sPattern))
                {
                    user.Tumblr = "http://" + user.Tumblr;
                }
                user.Tumblr = "/r.aspx?r=" + user.Tumblr + "&u=" + user.UserName + "&s=tumblr";
            }
            if (!string.IsNullOrEmpty(user.Formspring))
            {
                if (!Regex.IsMatch(user.Formspring, sPattern))
                {
                    user.Formspring = "http://" + user.Formspring;
                }
                user.Formspring = "/r.aspx?r=" + user.Formspring + "&u=" + user.UserName + "&s=formspring";
            }
            if (!string.IsNullOrEmpty(user.Stumbleupon))
            {
                if (!Regex.IsMatch(user.Stumbleupon, sPattern))
                {
                    user.Stumbleupon = "http://" + user.Stumbleupon;
                }
                user.Stumbleupon = "/r.aspx?r=" + user.Stumbleupon + "&u=" + user.UserName + "&s=stumbleupon";
            }
            if (!string.IsNullOrEmpty(user.Flickr))
            {
                if (!Regex.IsMatch(user.Flickr, sPattern))
                {
                    user.Flickr = "http://" + user.Flickr;
                }
                user.Flickr = "/r.aspx?r=" + user.Flickr + "&u=" + user.UserName + "&s=flickr";
            }
            if (!string.IsNullOrEmpty(user.Picasa))
            {
                if (!Regex.IsMatch(user.Picasa, sPattern))
                {
                    user.Picasa = "http://" + user.Picasa;
                }
                user.Picasa = "/r.aspx?r=" + user.Picasa + "&u=" + user.UserName + "&s=picasa";
            }
            if (!string.IsNullOrEmpty(user.Myspace))
            {
                if (!Regex.IsMatch(user.Myspace, sPattern))
                {
                    user.Myspace = "http://" + user.Myspace;
                }
                user.Myspace = "/r.aspx?r=" + user.Myspace + "&u=" + user.UserName + "&s=myspace";
               
            }
            if (!string.IsNullOrEmpty(user.Lastfm))
            {
                if (!Regex.IsMatch(user.Lastfm, sPattern))
                {
                    user.Lastfm = "http://" + user.Lastfm;
                }
                user.Lastfm = "/r.aspx?r=" + user.Lastfm + "&u=" + user.UserName + "&s=lastfm";
            }
            if (!string.IsNullOrEmpty(user.Youtube))
            {
                if (!Regex.IsMatch(user.Youtube, sPattern))
                {
                    user.Youtube = "http://" + user.Youtube;
                }
                user.Youtube = "/r.aspx?r=" + user.Youtube + "&u=" + user.UserName + "&s=youtube";
            }
            if (!string.IsNullOrEmpty(user.Foursquare))
            {
                if (!Regex.IsMatch(user.Foursquare, sPattern))
                {
                    user.Foursquare = "http://" + user.Foursquare;
                }
                user.Foursquare = "/r.aspx?r=" + user.Foursquare + "&u=" + user.UserName + "&s=foursquare";
            }
            if (!string.IsNullOrEmpty(user.Website1))
            {
                if (!Regex.IsMatch(user.Website1, sPattern))
                {
                    user.Website1 = "http://" + user.Website1;
                }
                user.Website1 = "/r.aspx?r=" + user.Website1 + "&u=" + user.UserName + "&s=website1";
            }
            if (!string.IsNullOrEmpty(user.Website2))
            {
                if (!Regex.IsMatch(user.Website2, sPattern))
                {
                    user.Website2 = "http://" + user.Website2;
                }
                user.Website2 = "/r.aspx?r=" + user.Website2 + "&u=" + user.UserName + "&s=website2";
            }
            if (!string.IsNullOrEmpty(user.Website3))
            {
                if (!Regex.IsMatch(user.Website3, sPattern))
                {
                    user.Website3 = "http://" + user.Website3;
                }
                user.Website3 = "/r.aspx?r=" + user.Website3 + "&u=" + user.UserName + "&s=website3";
            }
        }

        public string GetUserName()
        {
            return Request.QueryString["u"];
        }

        [WebMethod ]
        public static int Vote(string type)
        {
            if (HttpContext.Current.Session["userId"] == null)
            {
                return 1; // has to be login
            }
            else
            {
                VoteModel vote = new VoteModel();
                vote.VoterUserId = Convert.ToInt32(HttpContext.Current.Session["userId"].ToString());
                vote.Type = (type == "1") ? true : false;
                NameValueCollection collection = GetQueryStringCollection(HttpContext.Current.Request.UrlReferrer.Query);
                string userName = HttpContext.Current.Server.UrlDecode(collection["u"]);
                if (vote.Insert(userName))
                {
                    return 0; // ok
                }
                return 2; // already given
            }
        }
        
    }
}